package com.cuit.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cuit.pojo.Doctor;

/**
 * Servlet Filter implementation class d_Login
 */
@WebFilter(filterName = "d_LoginFilter", 
urlPatterns = {"/doctor_cm/*"})
public class d_LoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public d_LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html; charset=utf-8");	
		PrintWriter out = resp.getWriter();
		String requestURI = req.getRequestURI();		//获得发出请求的客户端URL地址
		String contextPath = req.getContextPath();		//获取当前应用的根目录
		if (requestURI.contains("/doctor_cm/login/doctor_register.jsp" )||requestURI.contains("/registerr" )) {
			System.out.println("是登录界面");
			chain.doFilter(request, response);		//直接放行	
		}
		else { //如果不是login页面，则过滤后再放行
			HttpSession session = req.getSession(true);
			Doctor d=(Doctor)session.getAttribute("doc");
			if (d!=null&&d.getId() != 0&&d.getPassword()!=null) {//不为null表示已登录
				System.out.println("登录了");
				chain.doFilter(request, response);
			} else {
				out.println("<h2>您没有登录，请先登录！2秒后回到登录页面。</h2>");
				resp.setHeader("refresh","2;url="+contextPath+"/doctor_cm/login/doctor_register.jsp");
				return;//终止过滤
			}

		}		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
